package com.karaoke.oksrv.service

import com.github.pagehelper.PageHelper
import com.github.pagehelper.PageInfo
import com.karaoke.oksrv.domain.QSong
import com.karaoke.oksrv.domain.Song
import com.karaoke.oksrv.mapper.master.SongMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * Created by allen on 2017/4/18.
 */
@Service
@CacheConfig(cacheNames = arrayOf("songs"))
@Transactional
class SongService
{
    @Cacheable(key = "#p0.hashCode()")
    fun getSongs(qSong: QSong): PageInfo<Song>
    {
        val page = PageHelper.startPage<Song>(qSong.page, qSong.size)
        when (qSong.queryType)
        {
            QSong.QueryType.QUERY_SINGER     ->
            {
                val srId = qSong.criteria as Int
                return page.doSelectPageInfo<Song> { songMapper.selectBySinger(srId) }
            }
            QSong.QueryType.QUERY_LANGUAGE   ->
            {
                val languageId: Int = qSong.criteria as Int
                return page.doSelectPageInfo<Song> { songMapper.selectByLanguage(languageId, qSong.keyword) }

            }
            QSong.QueryType.QUERY_NEW        ->
            {
                return page.doSelectPageInfo<Song> { songMapper.selectNew() }
            }
            QSong.QueryType.QUERY_WORD_COUNT ->
            {
                val count = qSong.criteria as Int
                return page.doSelectPageInfo { songMapper.selectWordCount(count) }
            }
            QSong.QueryType.QUERY_SONG_TYPE  ->
            {
                val langId = qSong.criteria as Int
                return page.doSelectPageInfo { songMapper.selectTypeId(qSong.typeId, langId) }
            }
            QSong.QueryType.QUERY_SEARCH     ->
            {
                return page.doSelectPageInfo { songMapper.selectSearch(qSong.keyword) }
            }
            QSong.QueryType.QUERY_RECOMMEND  -> return page.doSelectPageInfo { songMapper.selectRecommends() }
        }
    }

    @Cacheable(key = "'NewSongs'")
    fun getNewSongs(): List<Song>
    {
        return PageHelper.startPage<Song>(1, 100).doSelectPage<Song> { songMapper.selectNew() }
    }

    @Cacheable(key = "'HotSongs'")
    fun getHotSongs(): List<Song>
    {
        return PageHelper.startPage<Song>(1, 100).doSelectPage<Song> { songMapper.selectHots() }
    }

    @Cacheable(key = "'Recommends'")
    fun getRecommends(): List<Song>
    {
        return PageHelper.startPage<Song>(1, 100).doSelectPage<Song> { songMapper.selectRecommends() }
    }

    @Autowired lateinit var songMapper: SongMapper
}